import { ref } from 'vue';
import { pack, unpack } from 'rrweb';

// 状态管理
export const recordingState = ref({
  activeBuffer: 'A',
  lastSwitchTime: Date.now(),
  errorOccurred: false,
});

// Web Worker初始化
const recorderWorker = new Worker(
  new URL('./recorderWorker.js', import.meta.url),
  {
    type: 'module',
  }
);

let recordingDataResolver;

// 初始化时设置消息监听
recorderWorker.onmessage = ({ data }) => {
  if (data.type === 'RECORDING_DATA' && recordingDataResolver) {
    recordingDataResolver(data.events);
  }
};

// 错误处理函数
export async function captureError(errorData) {
  recordingState.value.errorOccurred = true;

  // 获取录制数据
  const eventData = await getRecordingData();

  // 准备发送数据
  const fullData = {
    ...errorData,
    userActions: eventData,
    metadata: {
      startTime: Date.now() - 30000,
      endTime: Date.now(),
    },
  };

  // 使用sendBeacon发送
  sendToBackend(fullData);
}

// 获取录制数据
function getRecordingData() {
  return new Promise((resolve) => {
    console.log('开始获取数据', resolve);
    recordingDataResolver = resolve;
    recorderWorker.postMessage({ type: 'REQUEST_DATA' });
  });
}

// 发送数据到后端
function sendToBackend(data) {
  const res = data.userActions;
  // const res = unpack(data.userActions);
  console.log(res);

  console.log('最后发送结果', JSON.stringify(data));
  // const url = 'your-backend-endpoint';
  // const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });

  // window.requestIdleCallback(() => navigator.sendBeacon(url, blob), {
  //   timeout: 3000,
  // });
}

// 定时切换缓冲区（每30秒）
setInterval(() => {
  if (recordingState.value.errorOccurred) return;

  const now = Date.now();
  if (now - recordingState.value.lastSwitchTime >= 30000) {
    recordingState.value.activeBuffer =
      recordingState.value.activeBuffer === 'A' ? 'B' : 'A';
    recordingState.value.lastSwitchTime = now;

    // 通知Worker切换缓冲区
    recorderWorker.postMessage({
      type: 'SWITCH_BUFFER',
      bufferName: recordingState.value.activeBuffer,
    });
  }
}, 1000);
